/**
 * Copyright(c) 2013-2013 by Puhuifinance Inc.
 * All Rights Reserved
 */
package com.puhui.chome.controller.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;

import com.puhui.chome.aop.ExceptionHttpStatus;
import com.puhui.chome.exception.ServiceException;
import com.puhui.chome.model.base.ReturnEntity;
import com.puhui.chome.util.DateUtil;

/**
 * @author dingxingang
 */
public class BaseController {

    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    public static final String RETURN_MESSAGE = "message";
    public static final String RETURN_ERROR = "error";
    public static final String RETURN_SUCCESS = "success";
    public static final String RETURN_ORDER = "order";
    public static final String RETURN_SORT = "sort";
    public static final String RETURN_ROWS = "rows";
    public static final String RETURN_TOTAL = "total";
    public static final String RETURN_ACTION_ID = "ActionId";
    public static final String RETURN_CALL_SHEET_ID = "CallSheetID";

    /**
     * 处理时间的转换器，默认格式是yyyy-MM-dd HH:mm:ss可以被重载
     * 
     * @param binder
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtil.DATETIME_PATTERN);
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }

    @ExceptionHandler
    public ResponseEntity<?> exp(Exception ex) {
        logger.info(ex.getMessage());
        if (ex instanceof ServiceException) {
            boolean flag = ex.getClass().isAnnotationPresent(ExceptionHttpStatus.class);
            if (flag) {
                return responseJsonError(ex.getMessage(),
                        ex.getClass().getAnnotation(ExceptionHttpStatus.class).status());
            }
        }

        return responseJsonError("服务器内部错误，请联系技术人员。", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    protected ResponseEntity<?> responseJsonSuccess(String msg) {
        ReturnEntity obj = new ReturnEntity(true, msg);
        return responseJson(obj, HttpStatus.OK);
    }

    protected ResponseEntity<?> responseJsonSuccess(String msg, Object result) {
        ReturnEntity obj = new ReturnEntity(true, msg, result);
        return responseJson(obj, HttpStatus.OK);
    }

    protected ResponseEntity<?> responseJsonError(String msg) {
        ReturnEntity obj = new ReturnEntity(false, msg);
        return responseJson(obj, HttpStatus.OK);
    }

    /**
     * 重载方法 ，增加一个返回实体
     * 
     * @author zhangming
     * @param msg
     * @param result
     * @return
     */
    protected ResponseEntity<?> responseJsonError(String msg, Object result) {
        ReturnEntity obj = new ReturnEntity(false, msg, result);
        return responseJson(obj, HttpStatus.OK);
    }

    /**
     * 发送Json对象到HTTP,请求并设置Cont-Type,防止IE提示下载对象
     * 
     * @param obj
     * @return
     */
    protected ResponseEntity<?> responseJson(ReturnEntity obj, HttpStatus status) {
        String contentType = "text/plain;charset=UTF-8";
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Content-Type", contentType);
        return new ResponseEntity<>(obj, responseHeaders, status);
    }

    /**
     * 返回错误信息
     * 
     * @param error
     * @param status
     * @return
     */
    private ResponseEntity<?> responseJsonError(String error, HttpStatus status) {
        String contentType = "text/plain;charset=UTF-8";
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Content-Type", contentType);
        return new ResponseEntity<>(error, responseHeaders, status);
    }

    /**
     * 文件下载
     * 
     * @param file
     * @param fileName
     * @param response
     * @throws IOException
     */
    public void downFile(File file, String fileName, HttpServletResponse response) {
        InputStream input = null;
        try {
            input = new FileInputStream(file);
            byte[] data = IOUtils.toByteArray(input);
            String ext = file.getName().split("\\.")[1];
            String fName = URLEncoder.encode(fileName + "." + ext, "UTF-8");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fName + "\"");
            response.addHeader("Content-Length", Integer.toString(data.length));
            response.setContentType("application/octet-stream; charset=UTF-8");
            IOUtils.write(data, response.getOutputStream());
        } catch (IOException e) {
            logger.error("文件下载异常,文件名称：{}", fileName, e);
        } finally {
            IOUtils.closeQuietly(input);
        }
    }

}